import { ElMessage } from 'element-plus';
import pinia from '/@/stores/index';
import useUserInfo from '/@/api/jdfsystem/user-info';
import { EmployeeInfoDetailModel } from '/@/interfaces/SystemserviceModel';
import { useEmployeeStore } from '/@/stores/employee-info';
import MESSAGE from '/@/enums/message-enum';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import type { FormInstance } from 'element-plus';
import { LoginPramModel } from '/@/interfaces/JdfsystemModel';

const hanldeUserInfo = useUserInfo();

async function handleCaptcha(width: number = 200, height: number = 200) {
    const res = await hanldeUserInfo.captcha({ param: { width: width, height: height }, pageInfo: undefined });
    return res.data;
}

async function handleLogin(loading: boolean, params: LoginPramModel) {
    loading = true;
    const res = await hanldeUserInfo.login({ param: params, pageInfo: undefined });
    const { code, data } = res.data;
    if (code === MESSAGE.OK) {
        console.info('Token=' + data);
        if (data) {
            await afterLogin(data);
        }
    }
    // 关闭loading
    loading = false;
}

async function afterLogin(token: string) {
    // 保存到session
    useEmployeeStore(pinia).setToken(token);
    await currentUser();

    // 登录成功提示
    let currentTimeInfo = formatAxis(new Date());
    const signInText = '欢迎回来！';
    ElMessage.success(`${currentTimeInfo}，${signInText}`);
    NextLoading.start();
}

async function currentUser() {
    const response = await hanldeUserInfo.detailByCurrent();
    const { code, data } = response.data;
    if (MESSAGE.OK === code) {
        const employee: EmployeeInfoDetailModel = {
            id: data.id,
            userId: data.id,
            employeeName: data.userName,
            employeeStatus: data.userStatus,
            employeeTel: undefined,
            email: undefined,
            headUrl: undefined,
            sex: 1,
            orgList: [],
            roleList: [],
            funcIdList: [],
            createTime: new Date(),
            updateTime: new Date(),
        };
        useEmployeeStore(pinia).setEmployeeInfo(employee);
    }
}

async function validateForm(formRel: FormInstance | undefined) {
    let flag = false;
    if (!formRel) {
        return flag;
    }
    await formRel.validate((valid, fields) => {
        console.info(fields);
        flag = valid;
    });
    return flag;
}

export {
    validateForm,
    handleLogin,
    handleCaptcha,
}